<?php
namespace App\Admin\Controllers\Inventory;

use App\Importer\Inventory\CNImporter;
use App\Models\Basics\SysArea;
use App\Models\Inventory\AreaCn;
use App\Models\Inventory\PublicCn;
use App\Models\Inventory\Transfer;
use App\Models\Product\ProductSku;
use App\Models\Stocking\StockingSku;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class TransferPUploadController extends AdminController{

    protected $title = '公共库存挪用';

    protected function grid()
    {
        return view('inventory.transfer-p-upload.index');
    }

    public function upload(Request $request){
        $iAreaId = $request->get('iarea_id');
        $pAreaId = SysArea::getSysAreaIdByArea();
        if($pAreaId == $iAreaId){
            admin_toastr('申请站点不能是PUBLIC','error');
            return back()->withInput();
        }
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $deductTransit = $request->get('deduct_transit');
            if($deductTransit == 1){
                $func = 'TransferDeduct';
            }else{
                $func = 'Transfer';
            }
            $re = $this->{'_import'.$func}($file,$iAreaId,$pAreaId);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importTransfer(UploadedFile $file,$iAreaId,$pAreaId){
        try{
            $data = Excel::toArray(new CNImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $userId = Admin::user()->id;
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $num = $row[1] ? trim($row[1]) : 0;
                if(!$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                if(!in_array($sku,$arr)){
                    $arr[$count] = $sku;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!is_numeric($num)){
                    $errors[$count] = '数量格式有误';
                    break;
                }
                if($num < 0){
                    $errors[$count] = '数量不能小于0';
                    break;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                DB::beginTransaction();
                $publicCn = PublicCn::getPublicCn($pSkuId);
                if(!$publicCn){
                    $errors[$count] = $sku.'公共库存不存在';
                    DB::rollBack();
                    continue;
                }
                if($publicCn->instant < $num){
                    $errors[$count] = $sku.'公共库存数量不足';
                    DB::rollBack();
                    continue;
                }
                $publicCn->instant -= $num;
                $flag1 = $publicCn->save();
                if(!$flag1){
                    $errors[$count] = $sku.'公共库存扣减失败';
                    DB::rollBack();
                    continue;
                }
                $areaCn = AreaCn::query()->firstOrNew(['area_id' => $iAreaId,'psku_id' => $pSkuId]);
                $areaCn->instant += $num;
                $flag2 = $areaCn->save();
                if(!$flag2){
                    $errors[$count] = $sku.'站点库存添加失败';
                    DB::rollBack();
                    continue;
                }
                $transfer = Transfer::query()->create([
                    'psku_id' => $pSkuId,
                    'iuser_id' => $userId,
                    'iarea_id' => $iAreaId,
                    'ouser_id' => $userId,
                    'oarea_id' => $pAreaId,
                    'deduct_transit' => 0,
                    'transfer_num' => $num,
                    'status' => 2,
                ]);
                if($transfer){
                    StockingSku::upCnInstant($iAreaId.'_'.$pSkuId);
                    DB::commit();
                }else{
                    $errors[$count] = $sku.'挪用记录添加失败';
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    private function _importTransferDeduct(UploadedFile $file,$iAreaId,$pAreaId){
        try{
            $data = Excel::toArray(new CNImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $userId = Admin::user()->id;
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $num = $row[1] ? trim($row[1]) : 0;
                if(!$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                if(!in_array($sku,$arr)){
                    $arr[$count] = $sku;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!is_numeric($num)){
                    $errors[$count] = '数量格式有误';
                    break;
                }
                if($num <= 0){
                    $errors[$count] = '数量必须大于0';
                    break;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                DB::beginTransaction();
                $publicCn = PublicCn::getPublicCn($pSkuId);
                if(!$publicCn){
                    $errors[$count] = $sku.'公共库存不存在';
                    DB::rollBack();
                    continue;
                }
                if($publicCn->instant < $num){
                    $errors[$count] = $sku.'公共库存数量不足';
                    DB::rollBack();
                    continue;
                }
                $publicCn->instant -= $num;
                $flag1 = $publicCn->save();
                if(!$flag1){
                    $errors[$count] = $sku.'公共库存扣减失败';
                    DB::rollBack();
                    continue;
                }
                $areaCn = AreaCn::query()->firstOrNew(['area_id' => $iAreaId,'psku_id' => $pSkuId]);
                if($areaCn->area_transit < $num){
                    $errors[$count] = $sku.'站点在途数量不足';
                    DB::rollBack();
                    continue;
                }
                $areaCn->area_transit -= $num;
                $areaCn->instant += $num;
                $flag2 = $areaCn->save();
                if(!$flag2){
                    $errors[$count] = $sku.'站点库存添加失败';
                    DB::rollBack();
                    continue;
                }
                $transfer = Transfer::query()->create([
                    'psku_id' => $pSkuId,
                    'iuser_id' => $userId,
                    'iarea_id' => $iAreaId,
                    'ouser_id' => $userId,
                    'oarea_id' => $pAreaId,
                    'deduct_transit' => 1,
                    'transfer_num' => $num,
                    'status' => 2,
                ]);
                if($transfer){
                    DB::commit();
                }else{
                    $errors[$count] = $sku.'挪用记录添加失败';
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
